//
//  CommentViewController.m
//  Hxcsfw
//
//  Created by 企友软mac on 2018/7/4.
//  Copyright © 2018年 企友软mac. All rights reserved.
//

#import "CommentViewController.h"
#import "CommentViewCell.h"
#import "VideoDetailModel.h"
#import "IQKeyboardManager.h"

@interface CommentViewController ()<UITableViewDelegate, UITableViewDataSource, UITextViewDelegate> {
    int j;
    UITextView *_textView;
    UIButton *fsBtn;
}

@property (nonatomic, strong)UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIButton *btnInput;
@property (nonatomic,strong) NSMutableArray *QBPLArray;
@property (weak, nonatomic) IBOutlet UIView *tabbarView;

@property (nonatomic, strong) UIView *inputView;
@property (nonatomic, strong) UILabel *lbOfPlaceholder;
@property (nonatomic, strong) UIButton *btnSend;

@end

@implementation CommentViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"评论";
    [self loadRightBtn];
    [self.view addSubview:self.tableView];
    j = 1;
    _textView.delegate = self;
    _btnInput.layer.cornerRadius = 15;
    _btnInput.clipsToBounds = YES;
     _QBPLArray = [NSMutableArray array];//全部评论
    [self requestListDataStrNum:@"1" isRefresh:YES];
    [self notifyRequestListData];

    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    _inputView = [[UIView alloc]initWithFrame:CGRectMake(0, WSCREENH_HEIGHT, WSCREENH_WIDTH, 49)];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wkeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wkeyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)notifyRequestListData{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestListDataStrNum:@"1" isRefresh:YES];
        j = 1;
    }];

    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSString *num = [NSString stringWithFormat:@"%d",++j];
        [self requestListDataStrNum:num isRefresh:NO];
    }];
}

- (void)loadRightBtn {

    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn2 setImage:[UIImage imageNamed:@"more.png"] forState:UIControlStateNormal];
    btn2.frame = CGRectMake(0, 0, 30, 30);
    [btn2 addTarget:self action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBtn2 = [[UIBarButtonItem alloc]initWithCustomView:btn2];
    self.navigationItem.rightBarButtonItem = barBtn2;
}

- (void)rightClick:(UIButton *)btn {

    WLog(@"%@",self.strUrl);
    WLog(@"%@",self.shareTitle);
    WLog(@"%@",self.strID);
    WLog(@"%@",self.strType);

    NSString *theLast = [self.strUrl substringFromIndex:[self.strUrl length]-1];
    if (![theLast isEqualToString:@"?"]) {
        self.strUrl = [self.strUrl stringByAppendingString: @"?"];
    }

    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine),@(UMSocialPlatformType_QQ),@(UMSocialPlatformType_Qzone)]];
    // --- 设置分享面板的UI
    [UMSocialShareUIConfig shareInstance].shareTitleViewConfig.isShow = YES;//有无标题
    [UMSocialShareUIConfig shareInstance].shareCancelControlConfig.isShow = YES;//有无取消
    [UMSocialShareUIConfig shareInstance].shareTitleViewConfig.shareTitleViewTitleString = @"";//标题文字
    [UMSocialShareUIConfig shareInstance].shareCancelControlConfig.shareCancelControlText = @"取消";//取消文字
    [UMSocialShareUIConfig shareInstance].sharePageScrollViewConfig.shareScrollViewPageMaxItemWidth = 50;//每页Items的最大宽度(白圈的大小)
    [UMSocialShareUIConfig shareInstance].sharePageScrollViewConfig.shareScrollViewPageMaxItemHeight = 90;//每页Items的最大高度(背景的高低)

    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的1确定所选平台进行下一步操作
        /*
         详情
         */
        NSString *descrStr = [WShareUtil filterHTML:_strSummary];
        descrStr = [descrStr stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];//去掉特殊符号
        descrStr = [descrStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];//去掉左右两端的空格
        /*
         图片
         */
        NSURL *imgUrl = [NSURL URLWithString:_strImage];
        NSData *dateImg = [NSData dataWithContentsOfURL:imgUrl];

        if (dateImg == nil || dateImg.length <= 0) {
            UMShareWebpageObject *webO = [UMShareWebpageObject shareObjectWithTitle:self.shareTitle descr:descrStr thumImage:[UIImage imageNamed:@"logo_share.png"]];

            if ([self.strUrl isEqualToString:@"http://www.sx95113.com/wapfww/azsm"]) { //安装说明
                webO.webpageUrl = [NSString stringWithFormat:@"%@?source=zst",self.strUrl];
            }else{
                webO.webpageUrl = [NSString stringWithFormat:@"%@&source=zst",self.strUrl];
            }

            [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:[UMSocialMessageObject messageObjectWithMediaObject:webO] currentViewController:self completion:^(id result, NSError *error) {

                NSString *message = nil;
                if (!error) {
                    message = [NSString stringWithFormat:@"分享成功"];
                } else {
                    message = [NSString stringWithFormat:@"失败原因Code: %d\n",(int)error.code];
                }
            }];
        } else {
            UMShareWebpageObject *webO = [UMShareWebpageObject shareObjectWithTitle:self.shareTitle descr:descrStr thumImage:dateImg];

            if ([self.strUrl isEqualToString:@"http://www.sx95113.com/wapfww/azsm"]) { //安装说明
                webO.webpageUrl = [NSString stringWithFormat:@"%@?source=zst",self.strUrl];
            }else{
                webO.webpageUrl = [NSString stringWithFormat:@"%@&source=zst",self.strUrl];
            }

            [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:[UMSocialMessageObject messageObjectWithMediaObject:webO] currentViewController:self completion:^(id result, NSError *error) {

                NSString *message = nil;
                if (!error) {
                    message = [NSString stringWithFormat:@"分享成功"];
                } else {
                    message = [NSString stringWithFormat:@"失败原因Code: %d\n",(int)error.code];
                }
            }];
        }
    }];
}

- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WSCREENH_WIDTH, WSCREENH_HEIGHT - 49 -64 ) style:UITableViewStylePlain];
        _tableView.estimatedRowHeight = 44;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//去掉横线
        _tableView.rowHeight = UITableViewAutomaticDimension;//高度设置为自适应
    }
    return _tableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.QBPLArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *identCell = @"CommentCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identCell];

    if (cell == nil) {
        CommentViewCell *commentViewCell = [[[NSBundle mainBundle] loadNibNamed:@"CommentViewCell" owner:self options:nil] lastObject];

        if (self.QBPLArray.count > 0 && self.QBPLArray != nil) {
            //cell2.plrLB.text = [self.QBPLArray[indexPath.row] plr];//评论人
            commentViewCell.commentatorNameLb.text = @"网友";//评论人
            commentViewCell.commentDateLb.text = [self.QBPLArray[indexPath.row] fbsj];//发布时间

            NSString *strCon = [self.QBPLArray[indexPath.row] content];
            WLog(@"%@",strCon);

            if([strCon rangeOfString:@"<br />"].location != NSNotFound)
            {
                strCon = [strCon stringByReplacingOccurrencesOfString:@"<br />" withString:@""];
            }

            commentViewCell.commentConLb.text = strCon;//评论内容

            [UILabel changeSpaceForLabel:commentViewCell.commentConLb];

            CGSize maximumLbTitle = CGSizeMake(WSCREENH_WIDTH - 65, MAXFLOAT);
            CGSize expectSize = [commentViewCell.commentConLb sizeThatFits:maximumLbTitle];
            commentViewCell.commentConH.constant = expectSize.height;

            if ([self.QBPLArray[indexPath.row] reply] != nil || [self.QBPLArray[indexPath.row] reply] != NULL) {

                [UILabel changeSpaceForLabel:commentViewCell.replyLb];
                commentViewCell.replyLb.text = [[self.QBPLArray[indexPath.row] reply][0] valueForKey:@"content"];//回复内容

                WLog(@"%@",commentViewCell.replyLb.text);
                CGSize maximumLbTitle = CGSizeMake(WSCREENH_WIDTH - 83, MAXFLOAT);
                CGSize expectSize = [commentViewCell.replyLb sizeThatFits:maximumLbTitle];
//                commentViewCell.replyView.height = 29 + expectSize.height;
                commentViewCell.replyViewH.constant = 44 + expectSize.height;
            }else{
                commentViewCell.replyView.hidden = YES;
                commentViewCell.replyViewH.constant = 0;
            }
        }
        cell = commentViewCell;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)requestListDataStrNum:(NSString *)pageNum isRefresh:(BOOL)isRefresh{

    NSString *username;
    NSString *nologinuser = [WShareUtil getUUID];

    NSDictionary *parametersDict;
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"mode":@"native",@"service":@"comment",@"content":@{@"username":[WShareUtil sharedData].dicSession[@"nsrsbh"],@"revert":@"paginate",@"from":@"fwwb",@"id":_strID,@"pagesize":@"10",@"pagenumber":pageNum,@"apptype":@"ios"}};
    }else {
        parametersDict = @{@"mode":@"native",@"service":@"comment",@"content":@{@"nologinuser":nologinuser,@"revert":@"paginate",@"from":@"fwwb",@"id":_strID,@"pagesize":@"10",@"pagenumber":pageNum,@"apptype":@"ios"}};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    //    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};

    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
       
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if (isRefresh) {
            [self.QBPLArray removeAllObjects];
        }
        for (NSDictionary *dic in returnDic[@"data"]) {
            VideoDetailModel *vdModel = [VideoDetailModel mj_objectWithKeyValues:dic];
            [self.QBPLArray addObject:vdModel];
        }

        [_tableView reloadData];

        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];

        ///* --- 图片式提醒
        UIView *view = [self.tableView viewWithTag:10000];
        [view removeFromSuperview];
        HHNonePage *_nonePage = [[HHNonePage alloc]init];
        _nonePage = nil;
        if (_QBPLArray.count == 0) {
            _nonePage = [[HHNonePage alloc] initWithFrame:CGRectMake(0, -120, self.view.frame.size.width, self.view.frame.size.height)];
            _nonePage.tag = 10000;
            [self.tableView addSubview:_nonePage];
        }
        //*/

        if ([returnDic[@"data"] count] < 10) {
            // 拿到当前的上拉刷新控件，变为没有更多数据的状态
            [self.tableView.footer endRefreshingWithNoMoreData];
        }

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}

-(void)wkeyboardWillShow:(NSNotification *)notification
{
    //这样就拿到了键盘的位置大小信息frame，然后根据frame进行高度处理之类的信息
    CGRect frame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

    CGFloat endHeight = WSCREENH_HEIGHT - self.inputView.bounds.size.height - frame.size.height;

    _inputView.frame = CGRectMake(0, endHeight, WSCREENH_WIDTH, 49);
    //    _textView.text = _textViewQ.text;
    if ([_textView.text length] == 0) {
        [self.lbOfPlaceholder setHidden:NO];
        [fsBtn setUserInteractionEnabled:NO];
//        [fsBtn setBackgroundColor:[UIColor grayColor]];

    }else {
        [self.lbOfPlaceholder setHidden:YES];
        [fsBtn setUserInteractionEnabled:YES];
//        [fsBtn setBackgroundColor:[UIColor colorWithRed:0.09 green:0.69 blue:0.11 alpha:1]];
    }
    
}

/**
 *  键盘将要隐藏
 *
 *  @param notification 通知
 */
-(void)wkeyboardWillHidden:(NSNotification *)notification
{
    _inputView.frame = CGRectMake(0, WSCREENH_HEIGHT, WSCREENH_WIDTH, 49);
    UIView *bgView = [self.view viewWithTag:20000];
    [bgView removeFromSuperview];
    [self.btnSend setBackgroundImage:[UIImage imageNamed:@"fabiao2"] forState:UIControlStateNormal];
    [self.btnSend setUserInteractionEnabled:NO];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    [_textView resignFirstResponder];
    UIView *bgView = [self.view viewWithTag:20000];
    [bgView removeFromSuperview];
    
}

- (void)textViewDidChange:(UITextView *)textView {
    NSUInteger length = [textView.text length];
    NSRange range = NSMakeRange(length - 1, 1);
    if([[textView.text substringWithRange:range] isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
    }
    // 该判断用于联想输入, 限制输入字数500
    if (textView.text.length > 499 ) {
        _textView.text = [textView.text substringToIndex:500];
    }

    if ([textView.text length] == 0) {
        [self.lbOfPlaceholder setHidden:NO];
        [fsBtn setUserInteractionEnabled:NO];
//        [fsBtn setBackgroundColor:[UIColor grayColor]];

    }else {
        [self.lbOfPlaceholder setHidden:YES];
        [fsBtn setUserInteractionEnabled:YES];
//        [fsBtn setBackgroundColor:[UIColor colorWithRed:0.09 green:0.69 blue:0.11 alpha:1]];
    }
}

- (IBAction)inputTextBtnClick:(UIButton *)sender {
    UIView *bgView = [[UIView alloc]initWithFrame:self.view.bounds];
    bgView.backgroundColor = [UIColor grayColor];
    bgView.alpha = 0.4;
    bgView.tag = 20000;
    [self.view addSubview:bgView];

    _inputView.backgroundColor = [UIColor whiteColor];

    [self.view addSubview:_inputView];

    _textView = [[UITextView alloc]initWithFrame:CGRectMake(20, 9, WSCREENH_WIDTH - 20 - 80, 31)];
    _textView.layer.masksToBounds = YES;
    _textView.layer.cornerRadius = 15;
    _textView.delegate = self;
    _textView.backgroundColor = WRGBColor(239, 240, 241);
    _textView.textContainerInset = UIEdgeInsetsMake(7, 8, 0, 0);
    _textView.font = [UIFont systemFontOfSize:15];
    [_inputView addSubview:_textView];

    [_textView becomeFirstResponder];

    //    _textView.inputAccessoryView = nil;
    self.lbOfPlaceholder = [[UILabel alloc]initWithFrame:CGRectMake(35, 9, 120, 31)];
    self.lbOfPlaceholder.enabled = NO;
    self.lbOfPlaceholder.text = @"期待您的评论";
    self.lbOfPlaceholder.font = [UIFont systemFontOfSize:12];
    self.lbOfPlaceholder.textColor = WRGBColor(150, 150, 150);
    [_inputView addSubview:self.lbOfPlaceholder];

    // 限制500字内容
    //    self.lbWBZContent = [[UILabel alloc]initWithFrame:CGRectMake(20, 95, 200, 21)];
    //    self.lbWBZContent.enabled = NO;
    //    self.lbWBZContent.text = @"限制500字内容";
    //    self.lbWBZContent.font = [UIFont systemFontOfSize:12];
    //    self.lbWBZContent.textColor = [UIColor greenColor];
    //    [_inputView addSubview:self.lbWBZContent];

    //发送按钮
    fsBtn = [[UIButton alloc]initWithFrame:CGRectMake(WSCREENH_WIDTH - 70, 9, 60, 31)];
    [fsBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [fsBtn setTitle:@"发布" forState:UIControlStateNormal];
    [fsBtn setUserInteractionEnabled:NO];
    [fsBtn setTitleColor:WRGBColor(88, 131, 251) forState:UIControlStateNormal];
//    [fsBtn setTintColor:[UIColor whiteColor]];
//    [fsBtn setBackgroundColor:[UIColor grayColor]];
    [fsBtn addTarget:self action:@selector(fsClick) forControlEvents:UIControlEventTouchUpInside];

    [_inputView addSubview:fsBtn];
}

-(void)fsClick {
    WLog(@"上发送");
    WLog(@"%@",_textView.text);
    // 判断输入内容是否有表情，有则不能提交
    if ([_textView.text stringContainsEmoji:_textView.text]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"评论内容暂不支持表情" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        _textView.text = @"";
        return;
    }

    if ([_textView.text disable_emoji:_textView.text]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"评论内容暂不支持表情" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        _textView.text = @"";
        return;
    }

    [self requestDataSubmitComment];
    [[IQKeyboardManager sharedManager] doneAction:nil];
}

#pragma mark - 提交评论
-(void)requestDataSubmitComment {
    /*
     mode:native,service:comment,content:{revert:submit,username:？,dto:{from:xt,id:?,content=?}}
     */
    NSString *username;
    NSDictionary *parametersDict;
    NSString *nologinuser = [WShareUtil getUUID];
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"mode":@"native",@"service":@"comment",@"content":@{@"revert":@"submit",@"username":[WShareUtil sharedData].dicSession[@"nsrsbh"],@"dto":@{@"from":@"fwwb",@"id":_strID,@"content":_textView.text}}};
    }else {
        parametersDict = @{@"mode":@"native",@"service":@"comment",@"content":@{@"revert":@"submit",@"nologinuser":nologinuser,@"dto":@{@"from":@"fwwb",@"id":_strID,@"content":_textView.text}}};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};

    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if([returnDic[@"resultCode"] isEqualToString:@"SUCCEED"]){

            //            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:@"评论提交成功！" delegate:nil cancelButtonTitle:SURE otherButtonTitles:nil];
            //            [alert show];
            //            return;
            [self requestListDataStrNum:@"1" isRefresh:YES];//下载详情评论列表
            j = 1;
            [self.tableView scrollsToTop];

        }else if([returnDic[@"resultCode"] isEqualToString:@"DTO_ERROR"]){

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ALERT_TITLE message:@"提交数据格式错误！" delegate:nil cancelButtonTitle:SURE otherButtonTitles:nil];
            [alert show];
            return;
        }

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}


@end
